package io;

import java.io.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description: 递归遍历目录查找文件，按照文件的内容查询
 * User: Li_yizYa
 * Date: 2025/5/8
 * Time: 19:09
 */
public class Practice3 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入要搜索的路径: ");
        String rootPath = scanner.next();
        File rootFile = new File(rootPath);
        if (!rootFile.isDirectory()) {
            System.out.println("要搜索的路径有误!");
            return;
        }
        System.out.print("请输入要搜索的查询词: ");
        String key = scanner.next();

        // 进行递归
        scan(rootFile, key);
    }

    private static void scan(File rootFile, String key) {
        if (!rootFile.isDirectory()) {
            return;
        }
        File[] files = rootFile.listFiles();
        if (files == null || files.length == 0) {
            return;
        }
        for (File file : files) {
            if (file.isFile()) {
                //  进行后续的查询操作
                doSearch(file, key);
            } else {
                // 递归
                scan(file, key);
            }
        }
    }

    private static void doSearch(File file, String key) {
        // 打开文件，读取文件内容，判断文件内容是否包含 key
        StringBuilder stringBuilder = new StringBuilder();

        try (Reader reader = new FileReader(file)) {
            char[] buffer = new char[1024];
            while (true) {
                int n = reader.read(buffer);
                if (n == -1) {
                    break;
                }
                String str = new String(buffer, 0, n);
                stringBuilder.append(str);
            }
//            if (!stringBuilder.toString().contains(key)) {
//                return;
//            }
            if (stringBuilder.indexOf(key) == -1) {
                // 未找到
                return;
            }
            // 找到了
            System.out.println("找到匹配的文件: " + file.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
